using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;

namespace net.notdot.Attercop.Client
{
    [Serializable]
    public class UserSettings : net.notdot.Attercop.UserSettings
    {
        public Dictionary<string, PathNode> SharedDirectories = new Dictionary<string,PathNode>();
        
        public readonly TreeBuilder TreeBuilder = new TreeBuilder(HashCache.Instance, Program.HashTasks);

        public UserSettings() : base() { }

        protected UserSettings(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            string[] paths = (string[]) info.GetValue("SharedDirectories", typeof(string[]));
            for (int i = 0; i < paths.Length; i++)
            {
                SharedDirectories.Add(paths[i], TreeBuilder.BuildTree(paths[i]));
            }
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            string[] paths = new string[SharedDirectories.Count];
            SharedDirectories.Keys.CopyTo(paths, 0);
            info.AddValue("SharedDirectories", paths);
        }

        private string m_filename;

        public static UserSettings Load(string filename)
        {
            UserSettings ret;
            if (!File.Exists(filename))
            {
                ret = new UserSettings();
            } else
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream s = new FileStream(filename, FileMode.Open, FileAccess.Read);
                ret = (UserSettings)formatter.Deserialize(s);
                s.Close();
            }

            ret.m_filename = filename;

            return ret;
        }

        public override void Save()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream s = new FileStream(m_filename, FileMode.OpenOrCreate, FileAccess.Write);
            formatter.Serialize(s, this);
            s.Close();
        }
    }
}
